package com.start.client.app.global;

import com.start.client.app.entity.ClientAppEntity;
import com.start.client.app.event.StartAppClientEvent;
import com.start.common.tools.SpringContextTools;
import com.start.common.tools.StartMapTools;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

public class DispatcherStartAppClientEvent implements StartAppClientEvent {
    private List<StartAppClientEvent> globalEvent;
    private List<StartAppClientEvent> allEvent;
    private Map<String, List<StartAppClientEvent>> appIdEventMap;
    private static boolean isLoad = false;
    private static DispatcherStartAppClientEvent appClientEvent = new DispatcherStartAppClientEvent();

    public static DispatcherStartAppClientEvent getInstance() {
        return appClientEvent;
    }

    private List<StartAppClientEvent> getEvents() {
        if (isLoad) {
            return allEvent;
        }
        allEvent = new ArrayList<>();
        globalEvent = new ArrayList<>();
        appIdEventMap = new HashMap<>();
        Map<String, StartAppClientEvent> beans = SpringContextTools.getBeans(StartAppClientEvent.class, false);
        if (beans == null || beans.isEmpty()) {
            isLoad = true;
            return allEvent;
        }
        Collection<StartAppClientEvent> values = beans.values();
        for (StartAppClientEvent event : values) {
            if (StringUtils.isBlank(event.appIds())) {
                globalEvent.add(event);
                continue;
            }
            StartMapTools.mapAddValue(appIdEventMap, event, event.appIds(), event.SPLIT());
        }
        isLoad = true;
        return allEvent;
    }

    @Override
    public String appIds() {
        return null;
    }

    @Override
    public void beforeAppDownloadInfo(String appId) {
        getEvents();
        List<StartAppClientEvent> events = appIdEventMap.getOrDefault(appId, null);
        if (events != null && !events.isEmpty()) {
            for (StartAppClientEvent event : events) {
                event.beforeAppDownloadInfo(appId);
            }
        }
        events = globalEvent;
        if (!events.isEmpty()) {
            for (StartAppClientEvent event : events) {
                event.beforeAppDownloadInfo(appId);
            }
        }
    }

    @Override
    public void afterAppDownloadInfo(ClientAppEntity entity) {
        getEvents();
        List<StartAppClientEvent> events = appIdEventMap.getOrDefault(entity.getAppId(), null);
        if (events != null && !events.isEmpty()) {
            for (StartAppClientEvent event : events) {
                event.afterAppDownloadInfo(entity);
            }
        }
        events = globalEvent;
        if (!events.isEmpty()) {
            for (StartAppClientEvent event : events) {
                event.afterAppDownloadInfo(entity);
            }
        }
    }
}
